#  -*- coding: utf-8 -*-

from pymongo import UpdateOne,ASCENDING, DESCENDING
from monitor.base_monitor import BaseMonitor
from data.finance_report_crawler import FinanceReportCrawler
from data.data_module import DataModule
from util.stock_util import get_all_codes,get_all_indexes_date,calc_negative_diff_dates,multi_computer,get_code_name
from util.database import DB_CONN
import time
import pandas as pd
from datetime import datetime, timedelta

"""
实现某一时期最佳板块的计算
"""


class BestBlockMonitor(BaseMonitor):
    def __init__(self):
        BaseMonitor.__init__(self, name='best_block')



    def monitoring(self, begin_date, end_date):
        """
        计算指定时间范围内板块涨幅排名
        """
        start_time = time.time()
        dm = DataModule()

        if begin_date is None:
            begin_date = "1990-12-19"

        #begin_date存在的指数，end_date一定存在
        codes = get_all_indexes_date(begin_date)
        codes_count = len(codes)
        block_rank_date_df = pd.DataFrame(columns=["relative_ratio","name","rank"],index=codes)
        i = 0
        #找到begin_date和end_date当日所有指数数据，以code为索引
        begin_df = dm.get_one_day_k_data(is_index=True, autype=None, period='D', date=begin_date)
        if begin_df.index.size > 0:
            begin_df.set_index(['code'], 1, inplace=True)

        end_df = dm.get_one_day_k_data(is_index=True, autype=None, period='D', date=end_date)
        if end_df.index.size > 0:
            end_df.set_index(['code'], 1, inplace=True)


        for code in codes:
            begin_close =begin_df.loc[code]['close']
            end_close = end_df.loc[code]['close']

            block_rank_date_df.loc[code]["relative_ratio"] = round(100 * (end_close - begin_close) / begin_close, 2)
            block_rank_date_df.loc[code]["name"] = get_code_name(code,True)


        # 从大到小计算排名
        block_rank_date_df['rank'] = block_rank_date_df["relative_ratio"].rank(ascending=False)
        #按排名重新排序
        block_rank_date_df.sort_values(by="rank",inplace=True)
        #block_rank_date_df.to_csv(("From%sto%s_blockrank.csv" %(begin_date,end_date)),encoding='utf_8_sig')
        index_lst = ['沪深300','上证50','上证指数','深证成指','创业板指','中小板指','中证500']
        show_df = block_rank_date_df.copy()[(block_rank_date_df['rank'] <= 16) | (block_rank_date_df['name'].isin(index_lst))]
        show_df.sort_values(by="rank",inplace=True)

        return show_df

if __name__ == '__main__':
    # 执行因子的提取任务
    #hfq =HfqMAFactor()

    BestBlockMonitor().monitoring('2020-04-30', '2020-05-29')
